"""
查询、添加、修改操作
"""

from book_def import BookInfo
from file_op import FileOperation


class Operation:
    fo = None

    def __init__(self, path):
        self.fo = FileOperation(path)

    # 查询图书
    def query(self, isShow):
        if isShow:
            print(f'*************** 查询图书 ***************')
        books = self.fo.read_file()
        if len(books) == 0:
            print(f"目前还没有图书哦！")
        else:
            count = 1
            for book_info in books:
                print(f"序号：{count}\t书名：《{book_info.book}》\t作者：{book_info.author}\t价格：{book_info.price}")
                count += 1
            print(f"共有{count - 1}条图书信息!")
            print()
        return books

    # 添加图书
    def add(self):
        print(f'*************** 添加图书 ***************')
        book = input('请输入要添加的图书名：\n')
        author = input('请输入该书的作者：\n')
        price = float(input('请输入该书的价格：\n'))
        book_info = BookInfo(book, author, price)
        self.fo.write_file(book_info)
        print(f"添加成功！")
        print()

    # 删除图书
    def delete(self, isAgain):
        if isAgain:
            print(f'*************** 删除图书 ***************')
        books = self.query(False)
        if isAgain:
            count = input("请输入您要删除的图书序号：\n")
        else:
            count = input("输入错误，请重新输入您要删除的图书序号：\n")
        try:
            count = int(count)
            books.pop(count - 1)
            self.fo.clean_file()
            for book_info in books:
                self.fo.write_file(book_info)
            print(f"删除成功！")
            self.query(False)
        except ValueError | IndexError:
            self.delete(False)
